<?php
if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) {
	die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );
}

/**
*
* @package  RealEstateManager
* @copyright 2011 Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Rob de Cleen(rob@decleen.com); 
* Homepage: http://www.ordasoft.com
* @version: 2.1 free $
*
**/

$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path']	= JPATH_SITE;

require_once($mosConfig_absolute_path."/administrator/components/com_realestatemanager/compat.joomla1.5.php");
require_once($mosConfig_absolute_path."/administrator/components/com_realestatemanager/install.realestatemanager.helper.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/admin.realestatemanager.class.impexp.php");
require_once ($mosConfig_absolute_path."/administrator/components/com_realestatemanager/admin.realestatemanager.class.conf.php");
require_once ($mosConfig_absolute_path."/components/com_realestatemanager/realestatemanager.class.php");

$GLOBALS['realestatemanager_configuration'] = $realestatemanager_configuration;

if(!defined( '_JLEGACY' ))
{
 $GLOBALS['path'] = $mosConfig_live_site."/components/com_realestatemanager/images/";
}
else 
{
$GLOBALS['path'] = $mosConfig_live_site."/administrator/components/com_realestatemanager/images/";
}
$path = $GLOBALS['path'];


function com_install()
{

  global $database,$mosConfig_absolute_path,$mosConfig_live_site,$realestatemanager_configuration;



//**********************   begin check version PHP   ***********************
$is_warning = false;

if ( (phpversion()) < 5 ) { 
	?>
<center>
<table width="100%" border="0">
  <tr>
    <td>
      <code>Installation status: <font color="red">fault</font></code>
    </td>
  </tr>
  <tr>
    <td>
      <code><font color="red">This component works correctly under PHP version 5.0 and higher.</font></code>
    </td>
  </tr>
</table>
</center>

<?php
return '<h2><font color="red">Component installation fault</font></h2>';
}

//******************   end check version PHP   ******************************

//******************   begin check php-xml extension   *****************
if ( !(class_exists('domDocument')) ) {
$is_warning = true;
?>
<center>
<table width="100%" border="0">
  <tr>
    <td>
      <code><font color="red">PHP-Xml extension not found! In order for xml export to work, you need to compile PHP5 with support for the PHP-Xml extension!</font></code>
    </td>
  </tr>
</table>
</center>
<?php
}
//*******************   end check php-xml extension   **********************//********************   begin check CURL extension   ******************
if ( !(function_exists('curl_init')) ) {
$is_warning = true;
?>
<center>
<table width="100%" border="0">
  <tr>
    <td>
      <code><font color="red">CURL extension not found! In order for Photo download to work, you need to compile PHP5 with support for the CURL extension!</font></code>
    </td>
  </tr>
</table>
</center>
<?php
}
//****************   end check CURL extension   ***********************
//*************   begin check GD extension   *************************
if ( !(function_exists('imagefontwidth')) ) {
$is_warning = true;
?>
<center>
<table width="100%" border="0">
  <tr>
    <td>
      <code><font color="red">GD extension not found! In order for CAPTCHA picture works correctly, you need to compile PHP5 with support for the GD extension!</font></code>
    </td>
  </tr>
</table>
</center>
<?php
}
//************************   end check GD extension   ******************


//******************   database ******************

$tableList = $database->getTableList();
echo 'cheking database<br/>';

$table_prefix = $database->getPrefix();

if (array_search($table_prefix.'rem_version',$tableList)){
  $database->setQuery("SELECT * FROM #__rem_version");
  $version = $database->loadAssoc();
}

if (array_search($table_prefix.'rem_houses',$tableList)){
  $database->setQuery("SELECT * FROM #__rem_houses");
  $reallibr = $database->loadResult();
}
else $reallibr='';
  if ($reallibr) {
    echo 'database already exist<br/>';
    if(isset($version['number']))
    { //если база данных есть,  и она новая
      //nothin to do
      //echo "Updated";
    }
    else
    { //если база данных есть, но она старая
      //for now do nothing, because old database for joomla 1.6 not exist 
    }
  }  
  else {//если базы данных нет, создаем её
     
     echo 'install database <br/>';
      $query= "DROP TABLES IF EXISTS #__rem_houses,
        #__rem_main_categories,
        #__rem_categories,
				#__rem_rent,
				#__rem_rent_request,
				#__rem_buying_request,
				#__rem_review,
        #__rem_suggestion,
				#__rem_photos";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();

      $query= "CREATE TABLE IF NOT EXISTS #__rem_houses (
          id int(11) unsigned NOT NULL auto_increment,
          asset_id int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'FK to the #__assets table.',
          houseid varchar(20) NOT NULL default '0',
          catid int(11) NOT NULL default '0',
          sid int(11) NOT NULL default '0',
          fk_rentid int(11) default '0',

          description text NOT NULL default '',
          link varchar(250) NOT NULL default '',
          listing_type varchar(45) NOT NULL default '',
          price varchar(14) NOT NULL default '',
          priceunit varchar(14) NOT NULL default '',
          htitle varchar(200) NOT NULL default '',

          hcountry varchar(50) NOT NULL default '',
          hregion varchar(50) NOT NULL default '',
          hcity varchar(50) NOT NULL default '',
          hlocation varchar(100) NOT NULL default '',
          hlatitude varchar(20) NOT NULL default '',
          hlongitude varchar(20) NOT NULL default '',
          map_zoom varchar(5) NOT NULL default '',  

          bathrooms int(11) default '0',
          bedrooms int(11) default '0',
          broker varchar(100) default '',
          contacts varchar(250) default '',
          image_link varchar(200) default '',
          listing_status varchar(45) default '',
          price_type varchar(45) default '',
          property_type varchar(45) default '',
          provider_class varchar(45) default '',
          year varchar(4) default '1900',

          agent varchar(45) default '',
          area varchar(45) default '0',
          expiration_date date default '2030-01-01',
          feature varchar(100) default '',
          hoa_dues varchar(45) default '',
          lot_size varchar(45) default '0',
          model varchar(50) default '',
          property_taxes FLOAT(3,2) default '0.0',
          school varchar(45) default '',
          school_district varchar(45) default '',
          style varchar(45) default '',
          zoning varchar(45) default '',

          `checked_out` int(11) NOT NULL default '0',
          `checked_out_time` datetime NOT NULL default '0000-00-00 00:00:00',
          
          `ordering` int(11) NOT NULL default '0',
          `date` datetime NOT NULL default '0000-00-00 00:00:00',
          `hits` int(11) NOT NULL default '0',
          `edok_link` varchar(200) default '',
          `published` tinyint(1) NOT NULL default '0',
          `approved` tinyint(1) NOT NULL default '1',
          `country` VARCHAR(25) default '',
          `city` VARCHAR(25) default '',
          `owneremail` VARCHAR(50) default '',

          PRIMARY KEY  (`id`),
          INDEX (`catid`)

          ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      //echo 2;
      //exit;
      $query= "CREATE TABLE IF NOT EXISTS `#__rem_main_categories` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `parent_id` int(11) NOT NULL DEFAULT '0',
        `asset_id` int(10) unsigned NOT NULL DEFAULT '0' COMMENT 'FK to the #__assets table.',
        `title` varchar(255) NOT NULL DEFAULT '',
        `name` varchar(255) NOT NULL DEFAULT '',
        `alias` varchar(255) NOT NULL DEFAULT '',
        `image` varchar(255) NOT NULL DEFAULT '',
        `section` varchar(50) NOT NULL DEFAULT '',
        `image_position` varchar(30) NOT NULL DEFAULT '',
        `description` text NOT NULL,
        `published` tinyint(1) NOT NULL DEFAULT '0',
        `checked_out` int(11) unsigned NOT NULL DEFAULT '0',
        `checked_out_time` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
        `editor` varchar(50) DEFAULT NULL,
        `ordering` int(11) NOT NULL DEFAULT '0',
        `access` tinyint(3) unsigned NOT NULL DEFAULT '0',
        `count` int(11) NOT NULL DEFAULT '0',
        `params` text NOT NULL,
        PRIMARY KEY (`id`),
        KEY `cat_idx` (`section`,`published`,`access`),
        KEY `idx_access` (`access`),
        KEY `idx_checkout` (`checked_out`)
      ) ENGINE=MyISAM  DEFAULT  COLLATE utf8_general_ci AUTO_INCREMENT=46 ; ";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      $query= "CREATE TABLE IF NOT EXISTS `#__rem_photos` (
          `id` int(11) unsigned NOT NULL auto_increment,
          `fk_houseid` int(11),
          `thumbnail_img` varchar(250) default '',
          `main_img` varchar(250) default '',
          PRIMARY KEY  (`id`),
          FOREIGN KEY (`fk_houseid`) REFERENCES #__rem_houses(`id`)
          ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`;";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      $query= "CREATE TABLE IF NOT EXISTS `#__rem_rent` (
          `id` int(11) unsigned NOT NULL auto_increment,
          `fk_houseid` int(11) NOT NULL default 0,
          `fk_userid` int(11),
          `rent_from` datetime NOT NULL default '0000-00-00 00:00:00',
          `rent_until` datetime,
          `rent_return` datetime,
          `checked_out` int(11) NOT NULL default 0,
          `checked_out_time` datetime NOT NULL default '0000-00-00 00:00:00',
          `user_name` VARCHAR(150),
          `user_email` VARCHAR(100),
          `user_mailing` TEXT default '',
          PRIMARY KEY  (`id`),
          FOREIGN KEY (`fk_userid`) REFERENCES #__users(`id`),
          FOREIGN KEY (`fk_houseid`) REFERENCES #__rem_houses(`id`)
          ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`;";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      $query= "CREATE TABLE IF NOT EXISTS `#__rem_rent_request` (
          `id` int(11) unsigned NOT NULL auto_increment,
          `fk_houseid` int(11) NOT NULL default 0,
          `fk_userid` int(11),
          `rent_from` date NOT NULL default '0000-00-00',
          `rent_until` date,
          `rent_request` datetime NOT NULL default '0000-00-00 00:00:00',
          `checked_out` int(11) NOT NULL default 0,
          `checked_out_time` datetime NOT NULL default '0000-00-00 00:00:00',
          `user_name` VARCHAR(150),
          `user_email` VARCHAR(100),
          `user_mailing` TEXT default '',
          `status` int(1) default 0,
          PRIMARY KEY  (`id`),
          FOREIGN KEY (`fk_userid`) REFERENCES #__users(`id`),
          FOREIGN KEY (`fk_houseid`) REFERENCES #__rem_houses(`id`)
          ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`;";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      $query= "CREATE TABLE IF NOT EXISTS `#__rem_buying_request` (
            `id` int(11) unsigned NOT NULL auto_increment,
            `fk_houseid` int(11) NOT NULL default 0,
            `fk_userid` int(11),
            `buying_request` datetime NOT NULL default '0000-00-00 00:00:00',
            `checked_out` int(11) NOT NULL default 0,
            `checked_out_time` datetime NOT NULL default '0000-00-00 00:00:00',
            `customer_name` varchar(250) default '',
            `customer_email` varchar(250) default '',
            `customer_phone` TEXT default '',
            `customer_comment` TEXT default '',
            `status` int(1) default 0,
            PRIMARY KEY  (`id`),
            FOREIGN KEY (`fk_userid`) REFERENCES #__users(`id`),
            FOREIGN KEY (`fk_houseid`) REFERENCES #__rem_houses(`id`)
        ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`;";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      $query= "CREATE TABLE IF NOT EXISTS `#__rem_review` (
          `id` int(11) unsigned NOT NULL auto_increment,
          `fk_houseid` int(11) NOT NULL default 0,
          `fk_userid` int(11),
          `user_name` VARCHAR(150),
          `user_email` VARCHAR(100),
          `date` datetime NOT NULL default '0000-00-00 00:00:00',
          `rating` int(2) default 0,
          `title` varchar(250) default '',
          `comment` TEXT,
          PRIMARY KEY  (`id`),
          FOREIGN KEY (`fk_userid`) REFERENCES #__users(`id`),
          FOREIGN KEY (`fk_houseid`) REFERENCES #__rem_houses(`id`)
          ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`;";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      $query= "CREATE TABLE IF NOT EXISTS `#__rem_suggestion` (
            `id` int(11) unsigned NOT NULL auto_increment,
            `fk_userid` int(11),
            `user_name` VARCHAR(150),
            `user_email` VARCHAR(100),
            `date` datetime NOT NULL default '0000-00-00 00:00:00',
            `title` varchar(250) default '',
            `comment` TEXT,
            PRIMARY KEY  (`id`),
            FOREIGN KEY (`fk_userid`) REFERENCES #__users(`id`)
            ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`;";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
    
      $query= "CREATE TABLE IF NOT EXISTS #__rem_version (
            `id` int(11) unsigned NOT NULL auto_increment,
            `version` varchar(11) NOT NULL default 0,
            `number` varchar(11),
            PRIMARY KEY  (`id`),
            INDEX (`id`)
            ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      
      $vers = explode(' ',$realestatemanager_configuration['release']['version']);
      $query= "INSERT INTO #__rem_version (`version`,`number`) VALUES ('$vers[0]','$vers[1]')";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      $query= "CREATE TABLE IF NOT EXISTS #__rem_categories (
            `id` int(11) unsigned NOT NULL auto_increment,
            `iditem` int(11) NOT NULL default 0,
            `idcat` int(11),
            PRIMARY KEY  (`id`),
            FOREIGN KEY (`iditem`) REFERENCES #__rem_houses(`id`),
            FOREIGN KEY (`idcat`) REFERENCES #__rem_main_categories(`id`)
            ) ENGINE=MyISAM AUTO_INCREMENT=2 CHARACTER SET `utf8`";
      $database->setQuery($query);
      $database->query();
        echo $database->getErrorMsg();
      echo "end install database<br/>";
 }


//add simple data
$database->setQuery("SELECT * FROM #__rem_houses");
$realestateemanager = $database->loadResult();
if(!isset($realestateemanager)){
  mosRealEstateManagerImportExport :: importHousesXML( $mosConfig_absolute_path."/administrator/components/com_realestatemanager/exports/sample_data.xml",NULL );

  echo "Sample data loaded<br/>";
}
//******************   end database ******************




DMInstallHelper::setAdminMenuImages();



# Show installation result to user
?>
<center>
<table width="100%" border="0">
  <tr>
    <td>
      <strong>RealEstateManager</strong><br/>
      <br/>
      This component is published under the <a href="<?php echo $mosConfig_live_site."/components/com_realestatemanager/doc/LICENSE.txt"; ?>"
       target="new">License</a>.
    </td>
  </tr>
  <tr>
    <td>
      <code>Installation: <font color="green">succesful</font></code>
    </td>
  </tr>
</table>
</center>

<?php
if($is_warning) return '<h2><font color="red">The RealEstateManager Component installed with a warning about a missing PHP extension! Please read carefully and uninstall RealEstateManager. Next fix your PHP installation and then install RealEstateManager again.</font></h2>';
}